import 'package:canteen/menu_c_v.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:canteen/page/add_order_page.dart';
import 'package:canteen/userDetail.dart';
import 'package:flutter/material.dart';
import 'package:canteen/history_c_v.dart';
import 'package:excel/excel.dart' hide Border;
import 'package:path_provider/path_provider.dart';
import 'package:vibration/vibration.dart';
import '../class/dish.dart';
import '../class/ingredient.dart';
import '../class/order.dart';
import 'dart:ui';
import 'dart:io';
import 'package:share_plus/share_plus.dart';

class HistoryPage extends StatefulWidget {
  static String id = 'history_page';

  const HistoryPage({super.key});

  @override
  State<HistoryPage> createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  List<Order> selectedOrders = [];
  String selectedDepartment = '';
  List<String> exportType = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    selectedTime = time[0];
    date = DateTime.now().toString().substring(0, 10);
    if (user.type == 'ADMIN' || user.type == 'SUPERADMIN') {
      exportType = dishesWithCategory.keys.toList();
      exportType.insert(0, '全部');
      exportType.removeWhere((element) {
        if (setMealsWithCategory[element] != null) {
          if (setMealsWithCategory[element]!.isNotEmpty) {
            return true;
          }
          return false;
        } else {
          return false;
        }
      });
    } else {
      exportType.add(user.department);
    }
    selectedDepartment = exportType.first;
  }

  List mergeDAI(List<Order> orders) {
    Map<Dish, int> mergedDishes = {};
    Map<Ingredient, double> totalIngredients = {};
    for (var order in orders) {
      for (var dishEntry in order.dishes.entries) {
        if (dishEntry.key.category == selectedDepartment ||
            selectedDepartment == '全部') {
          mergedDishes.putIfAbsent(dishEntry.key, () => 0);
          mergedDishes[dishEntry.key] =
              mergedDishes[dishEntry.key]! + dishEntry.value;
          for (var ingredientEntry in dishEntry.key.components.entries) {
            totalIngredients.putIfAbsent(ingredientEntry.key, () => 0.0);
            totalIngredients[ingredientEntry.key] =
                totalIngredients[ingredientEntry.key]! +
                    ingredientEntry.value * dishEntry.value;
          }
        }
      }
      for (var setMealEntry in order.setMeals.entries) {
        for (var dishEntry in setMealEntry.key.dishes.entries) {
          if (dishEntry.key.category == selectedDepartment ||
              selectedDepartment == '全部') {
            mergedDishes.putIfAbsent(dishEntry.key, () => 0);
            mergedDishes[dishEntry.key] = mergedDishes[dishEntry.key]! +
                dishEntry.value * setMealEntry.value;
            for (var ingredientEntry in dishEntry.key.components.entries) {
              totalIngredients.putIfAbsent(ingredientEntry.key, () => 0.0);
              totalIngredients[ingredientEntry.key] =
                  totalIngredients[ingredientEntry.key]! +
                      ingredientEntry.value *
                          dishEntry.value *
                          setMealEntry.value;
            }
          }
        }
      }
    }
    return [mergedDishes, totalIngredients];
  }

  void triggerVibration() async {
    // 检查设备是否支持震动
    bool canVibrate = await Vibration.hasVibrator() ?? false;
    if (canVibrate) {
      // 触发一次短震动
      Vibration.vibrate(duration: 100);
    }
  }

  Future<void> exportExcel() async {
    //create excel
    var excel = Excel.createExcel();
    Sheet sheet1 = excel['Sheet1'];
    Sheet sheet2 = excel['Sheet2'];
    //add title to excel
    //total num
    sheet1.cell(CellIndex.indexByString('A1')).value = TextCellValue('合计');
    sheet2.cell(CellIndex.indexByString('A1')).value = TextCellValue('合计');
    String b = String.fromCharCode('A'.codeUnitAt(0) + 1);
    //dish or ingredient
    sheet1.cell(CellIndex.indexByString("${b}1")).value = TextCellValue("菜品");
    sheet2.cell(CellIndex.indexByString("${b}1")).value = TextCellValue("材料");
    b = String.fromCharCode(b.codeUnitAt(0) + 1);
    //private room
    for (var element in selectedOrders) {
      sheet1.cell(CellIndex.indexByString('${b}1')).value =
          TextCellValue(element.pRoom);
      sheet2.cell(CellIndex.indexByString('${b}1')).value =
          TextCellValue(element.pRoom);
      b = String.fromCharCode(b.codeUnitAt(0) + 1);
    }
    List dAI = mergeDAI(selectedOrders);
    Map<Dish, int> totalDishes = dAI[0];
    Map<Ingredient, double> totalIngredients = dAI[1];
    int rowCount = 2;
    //sheet1
    //add dishes to excel
    for (var element in totalDishes.keys) {
      sheet1.cell(CellIndex.indexByString('B$rowCount')).value =
          TextCellValue(element.name);
      sheet1.cell(CellIndex.indexByString('A$rowCount')).value =
          IntCellValue(totalDishes[element]!);
      for (var i = 'A'.codeUnitAt(0) + 2; i < b.codeUnitAt(0); i++) {
        sheet1
            .cell(CellIndex.indexByString('${String.fromCharCode(i)}$rowCount'))
            .value = IntCellValue(selectedOrders[i - 'A'.codeUnitAt(0) - 2]
                .totalDishes[element] ??
            0);
      }
      rowCount++;
    }
    sheet1.merge(CellIndex.indexByString('A$rowCount'),
        CellIndex.indexByString('$b$rowCount'));
    sheet1.cell(CellIndex.indexByString('A$rowCount')).value =
        TextCellValue('$date $selectedTime');
    //sheet2
    //add ingredients to excel
    rowCount = 2;

    sheet2.merge(CellIndex.indexByString('A$rowCount'),
        CellIndex.indexByString('$b$rowCount'));
    sheet2.cell(CellIndex.indexByString('A$rowCount')).value =
        TextCellValue('荤(单位)');
    rowCount++;

    for (var element
        in totalIngredients.keys.where((element) => element.type == '荤料')) {
      sheet2.cell(CellIndex.indexByString('B$rowCount')).value =
          TextCellValue('${element.name}(${element.unit})');
      sheet2.cell(CellIndex.indexByString('A$rowCount')).value =
          DoubleCellValue(totalIngredients[element]!);
      for (var i = 'A'.codeUnitAt(0) + 2; i < b.codeUnitAt(0); i++) {
        sheet2
            .cell(CellIndex.indexByString('${String.fromCharCode(i)}$rowCount'))
            .value = DoubleCellValue(selectedOrders[i - 'A'.codeUnitAt(0) - 2]
                .totalIngredients[element] ??
            0);
      }
      rowCount++;
    }
    sheet2.merge(CellIndex.indexByString('A$rowCount'),
        CellIndex.indexByString('$b$rowCount'));
    sheet2.cell(CellIndex.indexByString('A$rowCount')).value =
        TextCellValue('素(单位)');
    rowCount++;
    for (var element
        in totalIngredients.keys.where((element) => element.type == '素料')) {
      sheet2.cell(CellIndex.indexByString('B$rowCount')).value =
          TextCellValue('${element.name}(${element.unit})');
      sheet2.cell(CellIndex.indexByString('A$rowCount')).value =
          DoubleCellValue(totalIngredients[element]!);
      for (var i = 'A'.codeUnitAt(0) + 2; i < b.codeUnitAt(0); i++) {
        sheet2
            .cell(CellIndex.indexByString('${String.fromCharCode(i)}$rowCount'))
            .value = DoubleCellValue(selectedOrders[i - 'A'.codeUnitAt(0) - 2]
                .totalIngredients[element] ??
            0);
      }
      rowCount++;
    }
    sheet2.merge(CellIndex.indexByString('A$rowCount'),
        CellIndex.indexByString('$b$rowCount'));
    sheet2.cell(CellIndex.indexByString('A$rowCount')).value =
        TextCellValue('$date $selectedTime');

    // 获取外部存储的公共下载目录路径
    final directory = await getExternalStorageDirectory();
    final filePath =
        '${directory!.path}/exported_data${DateTime.now().toString().substring(0, 19)}.xlsx';

    // 保存 Excel 文件
    await File(filePath).writeAsBytes(excel.save()!);
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
            // side: BorderSide(color: Colors.tealAccent, width: 1),
          ),
          title: Text('提示'),
          content: Text('文件已保存，是否分享？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                // 使用 shareXFiles 进行分享
                await Share.shareXFiles([XFile(filePath)]);
                Navigator.of(context).pop();
              },
              child: Text('分享'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffbfbfb),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          '历史',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 60, right: 60, top: 15),
            child: Stack(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(vertical: 16),
                  decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                            offset: Offset(0, 1),
                            blurRadius: 2,
                            color: Colors.black.withOpacity(0.25))
                      ],
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(15)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      GestureDetector(
                        onTap: () async {
                          // 调用日期选择器
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate:
                                DateTime.now().subtract(Duration(days: 30)),
                            // 将 lastDate 设置为当前时间一年后
                            lastDate: DateTime.now().add(Duration(days: 365)),
                            textDirection: TextDirection.ltr,
                            currentDate: DateTime.now(),
                            cancelText: "取消",
                            confirmText: "确定",
                            errorFormatText: "格式错误",
                            errorInvalidText: "输入日期无效",
                            fieldLabelText: "month/day/year",
                            fieldHintText: "月/日/年",
                            initialDatePickerMode: DatePickerMode.day,
                            useRootNavigator: true,
                          );
                          // 如果选择了日期，则更新 date 变量
                          if (pickedDate != null) {
                            setState(() {
                              date = pickedDate.toString().substring(0, 10);
                            });
                          }
                        },
                        child: Text(
                          date,
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 6,
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6),
                        child: DropdownButton(
                            isDense: true,
                            elevation: 1,
                            borderRadius: BorderRadius.circular(15),
                            underline: SizedBox(),
                            icon: SizedBox(),
                            value: selectedTime,
                            items: time
                                .map(
                                  (e) => DropdownMenuItem(
                                    value: e,
                                    child: Text(
                                      e,
                                      style: TextStyle(
                                        color: Color(0xff2b3d85),
                                      ),
                                    ),
                                  ),
                                )
                                .toList(),
                            onChanged: (value) {
                              setState(() {
                                selectedTime = value!;
                              });
                            }),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6),
                        child: DropdownButton(
                            menuMaxHeight: 150,
                            isDense: true,
                            elevation: 1,
                            borderRadius: BorderRadius.circular(15),
                            underline: SizedBox(),
                            icon: SizedBox(),
                            value: selectedDepartment,
                            items: exportType
                                .map(
                                  (e) => DropdownMenuItem(
                                    value: e,
                                    child: Text(
                                      e,
                                      style: TextStyle(
                                        color: Color(0xff2b3d85),
                                      ),
                                    ),
                                  ),
                                )
                                .toList(),
                            onChanged: (value) {
                              setState(() {
                                selectedDepartment = value!;
                              });
                            }),
                      ),
                    ],
                  ),
                ),
                Positioned(
                  left: 8,
                  top: 8,
                  child: Container(
                    height: 12,
                    width: 12,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                          color: Colors.black.withOpacity(0.6), width: 0.5),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: ordersWithDate[date]?[selectedTime]?.length == null
                ? Text('暂无订单')
                : Container(
                    padding: EdgeInsets.all(15),
                    decoration:
                        BoxDecoration(borderRadius: BorderRadius.circular(25)),
                    child: GridView.builder(
                      itemCount: ordersWithDate[date]?[selectedTime]?.length,
                      itemBuilder: (context, index) {
                        return GestureDetector(
                          onLongPress: () {
                            triggerVibration();
                            selectedValuePR =
                                ordersWithDate[date]![selectedTime]![index]
                                    .pRoom;
                            Navigator.pushNamed(context, AddOrderPage.id,
                                arguments: {
                                  'order': ordersWithDate[date]?[selectedTime]
                                      ?[index],
                                  'isAdd': false,
                                }).then((value) {
                              setState(() {});
                            });
                          },
                          onTap: () {
                            setState(() {
                              selectedOrders.contains(ordersWithDate[date]![
                                      selectedTime]![index])
                                  ? selectedOrders.remove(ordersWithDate[date]![
                                      selectedTime]![index])
                                  : selectedOrders.add(ordersWithDate[date]![
                                      selectedTime]![index]);
                            });
                          },
                          child: Stack(
                            children: [
                              Container(
                                alignment: Alignment.center,
                                padding: EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 8),
                                decoration: BoxDecoration(
                                    boxShadow: [
                                      BoxShadow(
                                          offset: Offset(0, 1),
                                          blurRadius: 2,
                                          color: Colors.black.withOpacity(0.25))
                                    ],
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(15)),
                                child: Text(
                                  '${ordersWithDate[date]![selectedTime]![index].pRoom} ${ordersWithDate[date]![selectedTime]![index].dishes.isEmpty && ordersWithDate[date]![selectedTime]![index].setMeals.length == 1 ? '${ordersWithDate[date]![selectedTime]![index].setMeals.keys.first.name} × ${ordersWithDate[date]![selectedTime]![index].setMeals.values.first}' : ''}',
                                  style: TextStyle(fontSize: 16),
                                ),
                              ),
                              Positioned(
                                left: 8,
                                top: 8,
                                child: AnimatedContainer(
                                  height: 12,
                                  width: 12,
                                  decoration: BoxDecoration(
                                    color: selectedOrders.contains(
                                            ordersWithDate[date]![
                                                selectedTime]![index])
                                        ? Color(0xff6486f3)
                                        : null,
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                        color: Colors.black.withOpacity(0.6),
                                        width: 0.5),
                                  ),
                                  duration: Duration(milliseconds: 200),
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        childAspectRatio: 2,
                        crossAxisSpacing: 10,
                        mainAxisSpacing: 10,
                        crossAxisCount: 2,
                      ),
                    ),
                  ),
          ),
          AnimatedSwitcher(
            duration: Duration(milliseconds: 150),
            child: selectedOrders.isEmpty
                ? SizedBox()
                : Row(
                    key: ValueKey(selectedOrders.isEmpty),
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            selectedOrders.clear();
                          });
                        },
                        child: Container(
                          width: 100,
                          height: 45,
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(bottom: 10),
                          decoration: BoxDecoration(
                            color: Color(0xff6486f3),
                            borderRadius: BorderRadius.circular(
                                20), // 设置圆角半径，你可以根据需要调整这个值
                          ),
                          child: Text(
                            '清空',
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          exportExcel();
                        },
                        child: Container(
                          width: 100,
                          height: 45,
                          alignment: Alignment.center,
                          margin: EdgeInsets.only(bottom: 10),
                          decoration: BoxDecoration(
                            color: Color(0xff6486f3),
                            borderRadius: BorderRadius.circular(
                                20), // 设置圆角半径，你可以根据需要调整这个值
                          ),
                          child: Text(
                            '导出',
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                        ),
                      ),
                    ],
                  ),
          )
        ],
      ),
    );
  }
}
/*
  Future<void> exportExcel() async {
    //create excel
    var excel = Excel.createExcel();
    Sheet sheet = excel['Sheet1'];
    //self style
    CellStyle ingredientCellStyle =
        CellStyle(backgroundColorHex: ExcelColor.blue300);
    CellStyle dishCellStyle =
        CellStyle(backgroundColorHex: ExcelColor.blue700);
    CellStyle dishHeadCellStyle =
        CellStyle(backgroundColorHex: ExcelColor.amber700);
    CellStyle ingredientHeadCellStyle =
        CellStyle(backgroundColorHex: ExcelColor.amber300);
    CellStyle dishLastCellStyle =
    CellStyle(backgroundColorHex: ExcelColor.yellow700);
    CellStyle ingredientLastCellStyle =
    CellStyle(backgroundColorHex: ExcelColor.yellow300);

    CellStyle firstCellStyle = CellStyle(backgroundColorHex: ExcelColor.amber);
    CellStyle privateRoomStyle = CellStyle(backgroundColorHex: ExcelColor.blue);
    CellStyle lastStyle = CellStyle(backgroundColorHex: ExcelColor.yellow);

    //add title to excel
    //dish or ingredient
    sheet.cell(CellIndex.indexByString("A1"))
      ..value = TextCellValue("菜品/材料")
      ..cellStyle = firstCellStyle;
    String b = String.fromCharCode('A'.codeUnitAt(0) + 1);
    //private room
    for (var element in ordersWithDate[date]!) {
      sheet.cell(CellIndex.indexByString('${b}1'))
        ..value = TextCellValue(element.pRoom)
        ..cellStyle = privateRoomStyle;
      b = String.fromCharCode(b.codeUnitAt(0) + 1);
    }
    //total num
    sheet.cell(CellIndex.indexByString('${b}1'))
      ..value = TextCellValue('合计')
      ..cellStyle = lastStyle;
    Map<Dish, int> totalDishes = mergeDishes(ordersWithDate[date]!);
    Map<Ingredient, double> totalIngredients =
        calculateTotalIngredients(ordersWithDate[date]!);
    int rowCount = 2;

    //add dishes to excel
    for (var element in totalDishes.keys) {
      sheet.cell(CellIndex.indexByString('A$rowCount'))
        ..value = TextCellValue(element.name)
        ..cellStyle = dishHeadCellStyle;
      sheet.cell(CellIndex.indexByString('$b${rowCount}'))
        ..value = IntCellValue(totalDishes[element]!)
        ..cellStyle = dishLastCellStyle;
      for (var i = 'A'.codeUnitAt(0) + 1; i < b.codeUnitAt(0); i++) {
        sheet.cell(
            CellIndex.indexByString('${String.fromCharCode(i)}${rowCount}'))
          ..value = IntCellValue(
              ordersWithDate[date]![i - 'A'.codeUnitAt(0) - 1]
                      .totalDishes[element] ??
                  0)
          ..cellStyle = dishCellStyle;
      }
      rowCount++;
    }

    //add ingredients to excel
    for (var element in totalIngredients.keys) {
      sheet.cell(CellIndex.indexByString('A$rowCount'))
        ..value = TextCellValue('${element.name}(${element.unit})')
        ..cellStyle = ingredientHeadCellStyle;
      sheet.cell(CellIndex.indexByString('$b${rowCount}'))
        ..value = DoubleCellValue(totalIngredients[element]!)
        ..cellStyle = ingredientLastCellStyle;
      for (var i = 'A'.codeUnitAt(0) + 1; i < b.codeUnitAt(0); i++) {
        sheet.cell(
            CellIndex.indexByString('${String.fromCharCode(i)}${rowCount}'))
          ..value = DoubleCellValue(
              ordersWithDate[date]![i - 'A'.codeUnitAt(0) - 1]
                      .totalIngredients[element] ??
                  0)
          ..cellStyle = ingredientCellStyle;
      }
      rowCount++;
    }
    // 获取外部存储的公共下载目录路径
    final directory = await getExternalStorageDirectory();
    final filePath =
        '${directory!.path}/exported_data${DateTime.now().toString().substring(0, 19)}.xlsx';

    // 保存 Excel 文件
    await File(filePath).writeAsBytes(excel.save()!);
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
            // side: BorderSide(color: Colors.tealAccent, width: 1),
          ),
          title: Text('提示'),
          content: Text('文件已保存，是否分享？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                // 使用 shareXFiles 进行分享
                await Share.shareXFiles([XFile(filePath)]);
                Navigator.of(context).pop();
              },
              child: Text('分享'),
            ),
          ],
        );
      },
    );
  }
 */
